package com.bookmanagement.service.impl;

import com.bookmanagement.DTO.BorrowDTO;
import com.bookmanagement.constant.BookException;
import com.bookmanagement.entity.Book;
import com.bookmanagement.entity.BorrowRecord;
import com.bookmanagement.exception.BusinessException;
import com.bookmanagement.mapper.BookMapper;
import com.bookmanagement.mapper.BorrowRecordMapper;
import com.bookmanagement.mapper.UserMapper;
import com.bookmanagement.service.BorrowService;
import com.bookmanagement.utils.BaseContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author skyjay
 */
@Service
public class BorrowServiceImpl implements BorrowService {
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private BorrowRecordMapper borrowRecordMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    @Transactional
    public void borrow(BorrowDTO borrowDTO) {
        String currentId = BaseContext.getCurrentId();
        Integer userId = userMapper.queryByEmail(currentId).getId();
        Book book = bookMapper.getById(borrowDTO.getBookId());
        if (book == null) {
            throw new BusinessException(BookException.BOOK_NOT_FOUND);
        }
        if (book.getStock() <= 0) {
            throw new BusinessException(BookException.BOOK_NOT_AVAILABLE);
        }
        BorrowRecord borrowRecord = BorrowRecord.builder()
                .borrowTime(borrowDTO.getBorrowTime())
                .bookId(borrowDTO.getBookId())
                .dueTime(borrowDTO.getDueTime())
                .userId(Long.valueOf(userId))
                .status(0)
                .build();
        bookMapper.reduceStock(borrowDTO.getBookId());
        borrowRecordMapper.addRecord(borrowRecord);
    }

    @Override
    @Transactional
    public void back(Integer id) {
        Book book = bookMapper.getById(Long.valueOf(id));
        if (book == null) {
            throw new BusinessException(BookException.BOOK_NOT_FOUND);
        }
        bookMapper.addStock(id);
        borrowRecordMapper.setStatus(id, 1);
    }
}
